import configparser
import json
from configparser import ConfigParser
import re


class Settings():
    def __init__(self, mainWindow):
        self.ui = mainWindow.ui.settings
        self.mainWindow = mainWindow
        self.ui.btn_cancel.clicked.connect(self.cancel)
        self.ui.btn_submit.clicked.connect(self.submit)
        self.ui.edit_address.textChanged.connect(self.checkIP)

    def loadData(self):
        # 获取当前设置服务器ip地址
        self.ui.edit_address.setText(self.mainWindow.address)
        # 获取当前设置服务器端口号
        self.ui.spin_port.setValue(int(self.mainWindow.port))
        # 获取当前颜色风格
        if (self.mainWindow.isWhite):
            self.ui.box_color.setCurrentIndex(1)
        else:
            self.ui.box_color.setCurrentIndex(0)

    def submit(self):
        # 如果ip不规范，则返回
        if not self.is_ip(self.ui.edit_address.text()):
            return

        # 判断是否修改了设置，如果修改了设置，则保存并重启软件，如果没有，则等同于直接退出设置页面
        hasChange = True
        if self.ui.edit_address.text() == self.mainWindow.address \
                and str(self.ui.spin_port.value()) == self.mainWindow.port \
                and self.ui.box_color.currentText() == self.mainWindow.colorStyle:
            hasChange = False

        if hasChange:
            path = './settings.ini'
            config = ConfigParser()
            config.read(filenames=path, encoding='utf8')
            config.set('flask_qt', 'address', self.ui.edit_address.text())
            config.set('flask_qt', 'port', str(self.ui.spin_port.value()))
            config.set('flask_qt', 'style', self.ui.box_color.currentText())

            config.set('emergency', 'address', self.mainWindow.emergencyAddress)
            config.set('emergency', 'port', str(self.mainWindow.emergencyPort))
            config.set('emergency', 'username', self.mainWindow.emergencyUsername)
            config.set('emergency', 'password', self.mainWindow.emergencyPassword)

            config.write(open(path, 'w', encoding='utf8'))
            try:
                # 连带修改课题二动作训练ip配置
                with open(self.mainWindow.course_standard_path + 'data\dbconfig\database_account_password.json', 'r',
                          encoding="utf-8") as f:
                    standard_json = json.load(f)
                standard_json['video_ip'] = self.ui.edit_address.text() + ':' + str(self.ui.spin_port.value())
                with open(self.mainWindow.course_standard_path + 'data\dbconfig\database_account_password.json', 'w',
                          encoding="utf-8") as f:
                    json.dump(standard_json, f, indent=4, ensure_ascii=False)

                # 连带修改课题二心理ip配置
                with open(self.mainWindow.course_psychology_path + 'data\config\database_account_password.json', 'r',
                          encoding="utf-8") as f:
                    psychology_json = json.load(f)
                psychology_json['ip'] = self.ui.edit_address.text() + ':' + str(self.ui.spin_port.value())
                with open(self.mainWindow.course_psychology_path + 'data\config\database_account_password.json', 'w',
                          encoding="utf-8") as f:
                    json.dump(psychology_json, f, indent=4, ensure_ascii=False)

                # 连带修改课题二情绪训练ip配置
                with open(self.mainWindow.course_emotion_path + 'data\config\database_account_password.json', 'r',
                          encoding="utf-8") as f:
                    emo_json = json.load(f)
                emo_json['video_ip'] = self.ui.edit_address.text() + ':' + str(self.ui.spin_port.value())
                with open(self.mainWindow.course_emotion_path + 'data\config\database_account_password.json', 'w',
                          encoding="utf-8") as f:
                    json.dump(emo_json, f, indent=4, ensure_ascii=False)
            except:
                pass

            self.mainWindow.restart()
        else:
            self.cancel()

    def cancel(self):
        if self.mainWindow.isLogin:
            self.mainWindow.ui.stackedWidget.setCurrentWidget(self.mainWindow.ui.web.page_widgets)
        else:
            self.mainWindow.ui.stackedWidget.setCurrentWidget(self.mainWindow.ui.login.page_widgets)

    # 当ip地址输入栏变化时，修改判断ip地址是否合法
    def checkIP(self):
        if self.is_ip(self.ui.edit_address.text()):
            self.ui.label_ipERROR.setText('')
        else:
            self.ui.label_ipERROR.setText('请输入合法IP地址')

    # 判断一个字符串是否是ip地址
    def is_ip(self, ipAddr):
        check_ip = re.compile(
            '^(1\d{2}|2[0-4]\d|25[0-5]|[1-9]\d|[1-9])\.(1\d{2}|2[0-4]\d|25[0-5]|[1-9]\d|\d)\.(1\d{2}|2[0-4]\d|25[0-5]|[1-9]\d|\d)\.(1\d{2}|2[0-4]\d|25[0-5]|[1-9]\d|\d)$')
        if check_ip.match(ipAddr):
            return True
        else:
            return False
